package odbc;

//import java.sql.DatabaseMetaData;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

public class ConnectODBC {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {

			// Buoc 1 : load driver
			// com.microsoft.sqlserver.jdbc.SQLServerDriver
			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

			// Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
			System.out.println("load driver successfully.....");

			// Buoc 2 : get connection
			// String user = "sa";
			// String pass = "sa";
			/*
			 * Enumeration<Driver> d = DriverManager.getDrivers(); while
			 * (d.hasMoreElements()) { Driver driver = (Driver) d.nextElement();
			 * System.out.println(driver.getClass().getName()); }
			 */

			/*
			 * Connection conn =
			 * DriverManager.getConnection("jdbc:odbc:datasql", "sa", "123456");
			 */

			Connection conn = DriverManager.getConnection(
					"jdbc:sqlserver://BDK-PC:1433;databaseName=Demo", "sa",
					"123456");

			System.out.println("got connection.....");
			// // Buoc 3: create Statement && execute SQL command

			Statement state = conn.createStatement();
			// // execute command
			String sql = "SELECT * FROM sinhvien";
			ResultSet result = state.executeQuery(sql);
			//
			// DatabaseMetaData md = conn.getMetaData();// cho biet thong tin
			// cua database

			// // hien thi du lieu meta data
			ResultSetMetaData data = result.getMetaData();
			int column = data.getColumnCount();

			for (int i = 1; i <= column; i++) {
				System.out.print(data.getColumnName(i) + "\t");
				// System.out.print(data.getColumnTypeName(i) + "\t");
			}
			//
			System.out.println("\n" + "------------------------------------");
			//
			// // kiem tra xem trong ResultSet co du lieu khong
			while (result.next()) {
				System.out.println(result.getString("id") + "\t"
						+ result.getString("tensv") + "\t"
						+ result.getString("email"));
			}
			//
			// state.close();
			// conn.close();

		} catch (ClassNotFoundException ex) {
			ex.printStackTrace();
		} catch (SQLException ex) {
			ex.printStackTrace();
		}

	}
}
